//
//  SetBeacon123ViewController.swift
//  MTBLETools
//
//  Created by 方强 on 16/10/24.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit
import MBProgressHUD
import MTSDK

class SetBeacon123ViewController: UIViewController, UIActionSheetDelegate{
    
    class func getActivity() -> SetBeacon123ViewController{
        let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main);
        let vc = storyBoard.instantiateViewController(withIdentifier: "SetBeacon123ViewController") as! SetBeacon123ViewController;
        
        return vc;
    }
    
    var working_device:MTBLEDevice!;
    var pwd:String = "";
    private var mStaticDatas:StaticDatas!;
    override func viewDidLoad() {
        super.viewDidLoad()
        mStaticDatas = StaticDatas.getInstance();
        
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(keyboardHide));
        tapGestureRecognizer.cancelsTouchesInView = false;
        self.view.addGestureRecognizer(tapGestureRecognizer);
    }
    
    func keyboardHide(tap:UITapGestureRecognizer){
        self.view.endEditing(true);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 初始化控件
    @IBOutlet weak var parentView: UIView!
    @IBOutlet weak var major_edit: UITextField!
    @IBOutlet weak var minor_edit: UITextField!
    @IBOutlet weak var uuid_txt: UILabel!
    @IBOutlet weak var pwd_edit: UITextField!
    @IBOutlet weak var sendhz_edit: UITextField!
    @IBOutlet weak var measur_edit: UITextField!
    @IBOutlet weak var version_txt: UILabel!
    @IBOutlet weak var pwd_swith: UISwitch!
    @IBOutlet weak var uuid_spinertmp: UIView!
    private var uuid_spiner: ISGDropDownList?
    @IBOutlet weak var sendpower_spinertmp: UIView!
    private var sendpower_spiner: ISGDropDownList?
    private var uuidNames = [String]();
    private func initView(){
        
        if(uuid_spiner != nil){
            return;
        }
        
        for uuid in mStaticDatas.uuidList {
            uuidNames.append(uuid.getName());
        }
        uuid_spiner = ISGDropDownList(frame: CGRect(x: uuid_spinertmp.frame.minX, y: uuid_spinertmp.frame.minY, width: uuid_spinertmp.frame.width, height: uuid_spinertmp.frame.height));
        uuid_spiner!.listItems = uuidNames;
        uuid_spiner!.reloadData();
        
        uuid_spiner?.clickDropDown = {(index) in
            self.uuid_txt.text = self.mStaticDatas.uuidList[index].getUuid();
        };
        
        sendpower_spiner = ISGDropDownList(frame: CGRect(x: sendpower_spinertmp.frame.minX, y: sendpower_spinertmp.frame.minY, width: sendpower_spinertmp.frame.width, height: sendpower_spinertmp.frame.height));
        sendpower_spiner!.listItems = MTBeacon123Base.SendPowerName;
        sendpower_spiner!.reloadData();
        self.parentView.addSubview(uuid_spiner!);
        self.parentView.addSubview(sendpower_spiner!);
        
        initBLE();
    }
    
    @IBAction func navBtnOnclickAction(_ sender: UIBarButtonItem) {
        
        if(sender.tag == 1){  // 返回
            self.dismiss(animated: false, completion: {
                
            });
            return;
        }
        
        if(sender.tag == 2){  // 开始设置
            setDatas();
            return;
        }
        
    }

    @IBAction func MyOnclickAction(_ sender: UIButton) {
       
        if(sender.tag == 2){  // 临时部署
            setTmpDevelop();
            return;
        }

    }
    
    @IBAction func pwdOnChange(_ sender: UISwitch) {
        pwd_edit.isEnabled = pwd_swith.isOn;
    }
    
    // 初始化蓝牙
    private var manager:MTBLEManager!;
    private var scanCallback:MTBLEManager_ScanCallback!;
    private var ble:MTBeacon123Base!;
    private func initBLE(){
        manager = MTBLEManager.getInstance();
        ble = MTBeacon123Base(manager: manager);
        
        getBeaconDatas();
    }
    
    // 同步数据
    private var baseAlert:UIAlertView!;
    private func getBeaconDatas(){
        
        self.baseAlert = UIAlertView(title: "Inf", message: "读取参数。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert!.show();
        
        let callback = MTBeacon123Base_ReadInfsCallBack();
        callback.onSuccess = {(ble, datas) in
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
            
            self.major_edit.text  = "\(datas.getMajor())";
            self.minor_edit.text  = "\(datas.getMinor())";
            self.uuid_txt.text    = datas.getBeaconUUID()!;
            self.sendhz_edit.text = "\(datas.getSendhz())";
            self.measur_edit.text = "\(datas.getMeasuedPower())";
            self.version_txt.text = "固件版本:\(datas.getVersion()!)";
            
            self.sendpower_spiner?.selectedIndex = datas.getSendpower();
            
            var findit = false;
            
            for i in 0 ..< self.mStaticDatas.uuidList.count {
                if(self.mStaticDatas.uuidList[i].getUuid() == datas.getBeaconUUID()){
                    self.uuid_spiner?.selectedIndex = i;
                    findit = true;
                    break;
                }
            }

            if(!findit){ // 如果列表里面不存在这个uuid
                let newuuid = UuidAndName(name: "未命名", uuid: datas.getBeaconUUID()!);
                newuuid.setId(id: UuidAndName.add(database: self.mStaticDatas.db, device: newuuid));
                self.mStaticDatas.uuidList.append(newuuid);
                self.uuidNames.append("未命名");
                self.uuid_spiner?.selectedIndex = self.uuidNames.count-1;
            }
        };
        
        callback.onFail = {(ble, errocode) in
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "读取参数失败->\(errocode.getMsg())");
        };
        
        let errocode = ble.readAllInf(device: working_device, pwd: pwd, readinfscallback: callback);
        
        if(errocode.getCode() != 0){
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "读取参数败->\(errocode.getMsg())");
        }
    }
    
    // 设置数据
    private func setDatas(){
        let datas = MTBeaconInfModel();
        
        // major
        if((major_edit.text == nil) || (major_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (major_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 5)){
            self.showFailAlert(erromsg: "major erro");
            return;
        }
        let major = Int(major_edit.text!)!;
        if ((major<0) || (major>65535)) {
            self.showFailAlert(erromsg: "major erro");
            return;
        }
        datas.setMajor(major: major);
        
        // minor
        if((minor_edit.text == nil) || (minor_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (minor_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 5)){
            self.showFailAlert(erromsg: "minor erro");
            return;
        }
        let minor = Int(minor_edit.text!)!;
        if ((minor<0) || (minor>65535)) {
            self.showFailAlert(erromsg: "minor erro");
            return;
        }
        datas.setMinor(minor: minor);
        
        // measur
        if((measur_edit.text == nil) || (measur_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (measur_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 2)){
            self.showFailAlert(erromsg: "measure erro");
            return;
        }
        let measure = Int(measur_edit.text!)!;
        if ((measure<0) || (measure>99)) {
            self.showFailAlert(erromsg: "measure erro");
            return;
        }
        datas.setMeasuedPower(measuedPower: measure);
        
        // UUID
        datas.setBeaconUUID(beaconUUID: uuid_txt.text!);
        
        // Hz
        if((sendhz_edit.text == nil) || (sendhz_edit.text!.lengthOfBytes(using: String.Encoding.utf8) == 0) || (sendhz_edit.text!.lengthOfBytes(using: String.Encoding.utf8) > 4)){
            self.showFailAlert(erromsg: "广播频率 erro");
            return;
        }
        let hz = Int(sendhz_edit.text!)!;
        if ((hz<100) || (hz>2000)) {
            self.showFailAlert(erromsg: "广播频率 erro");
            return;
        }
        datas.setSendhz(sendhz: hz);
        
        // power
        datas.setSendpower(sendpower: sendpower_spiner!.selectedIndex);
        
        // pwd
        if(pwd_swith.isOn){
            if((pwd_edit.text == nil) || ((pwd_edit.text!.lengthOfBytes(using: String.Encoding.utf8) != 0) && (pwd_edit.text!.lengthOfBytes(using: String.Encoding.utf8) != 6))){
                self.showFailAlert(erromsg: "密码必须6位");
                return;
            }
            datas.setNewpwd(newpwd: pwd_edit.text!);
        }
        
        self.baseAlert = UIAlertView(title: "Inf", message: "设置数据。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert!.show();
        
        let callback = MTBeacon123Base_BaseCallBack();
        
        callback.onSuccess = {(ble) in
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
        };
        callback.onFail = {(ble, errocode) in
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "设置数据失败->\(errocode.getMsg())");
        };
        
        let errocode = ble.setAllParamters(device: working_device, pwd: pwd, deviceinf: datas, callback: callback);
        if(errocode.getCode() != 0){
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "设置数据失败->\(errocode.getMsg())");
        }
    }
    
    // 临时部署
    private func setTmpDevelop(){
        
        self.baseAlert = UIAlertView(title: "Inf", message: "临时部署。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert!.show();
        
        let cmdAction = WriteCharactWithAckAction(sendCharact: nil, reviceCharact: nil, datas: "AT+DEPLOY".data(using: String.Encoding.utf8), option: BLEBaseAction_ActionOption(timeout: 1000));
        
        cmdAction.onReciveDatas = {(action, charact, datas) in
            action.setStatues(statues: BLEBaseAction_ActionStatues.DONE);
            self.ble.disConnect();
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
        };
        
        cmdAction.onFail = {(action, errocode) in
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
            self.ble.disConnect();
            self.showFailAlert(erromsg: "临时部署失败->\(errocode.getMsg())");
        };
        
        let errocode = ble.sendATCMD(device: working_device, pwd: pwd, action: cmdAction);
        
        if(errocode.getCode() != 0){
            self.baseAlert!.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "临时部署失败->\(errocode.getMsg())");
        }
    }
    
    // 显示失败对话框
    private func showFailAlert(erromsg: String){
        baseAlert = UIAlertView(title: "Fail", message: erromsg, delegate: nil, cancelButtonTitle: "OK");
        baseAlert.show();
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    @IBAction func TextFinish(_ sender: UITextField) {
        sender.resignFirstResponder();
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.view.openKeyboardOffsetView();
        
        initView();
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated);
        self.view.closeKeyboardOffsetView();
    }

}
